package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 控制器
 *
 * @author lhn
 * @date 2022/04/10 14:33
 * @since 1.0.0
 **/
@RestController
@RequiredArgsConstructor
@Slf4j
public class PaymentController {

    private final PaymentService paymentService;

    @Value("${server.port}")
    private String serverPost;

    /**
     * 对于注册到 Eureka 里面的微服务，可以通过服务发现来获得该服务的信息
     */
    private final DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult createPayment(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("***********插入结果：{}", result);
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功！服务对应的端口号：" + serverPost, result);
        } else {
            return new CommonResult(444, "插入数据库失败！");
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult <Payment> createPayment(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("***********查询结果：{}", payment);
        if (payment != null) {
            return new CommonResult(200, "查询数据成功！服务对应的端口号：" + serverPost, payment);
        } else {
            return new CommonResult(444, "查询数据失败！");
        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List <String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("*** element：{}", service);
        }
        // 获取一个微服务名称下的所有实例
        List <ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("{}\t{}\t{}\t{}", instance.getInstanceId(), instance.getHost(), instance.getPort(), instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        return serverPost;
    }

    @GetMapping(value = "/payment/feign/timout")
    public String paymentFeignTimout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPost;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return "hi ,i am zipkin";
    }
}